﻿// Convert divs to queue widgets when the DOM is ready
var selected_id = new Array();
var selected_path = new Array();
var foto;
var categ;



$(function () {
    categ = $('#categoria').val();
    caricaTabellaFoto(categ);

    $("#renameAlbumForm").dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true,
        buttons: {
            "Rinomina": function () {
                var newName = $('#newName').val();
                if (newName.length > 0) {
                    var id = $('#newName').attr('old');
                    if (!AlbumExist(newName)) {
                        if (RenameAlbum(id, newName)) {
                            $("#renameAlbumForm").dialog('close');
                            window.location.href = "ModifyAlbum?id=" + id;
                        }
                        else {
                            $("#errorMessage").text("Errore nella rinominzione dell'album");
                        }
                    }
                    else {
                        $("#errorMessage").text("Nome già esistente");
                    }
                }
                else
                    $("#errorMessage").text("Inserire un nuovo nome");
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        },
        close: function () {
            //allFields.val("").removeClass( "ui-state-error" );
        }
    });



    $("#uploader").plupload({
        // General settings
        runtimes: 'html5,browserplus,silverlight,gears,html4,flash',
        url: '/Foto/UploadFoto?categoria=' + categ,
        data: { categoria: categ },
        max_file_size: '1000mb',
        max_file_count: 20, // user can add no more then 20 files at a time
        chunk_size: '20mb',
        unique_names: false,
        multiple_queues: true,
        // Resize images on clientside if we can
        //resize : {width : 320, height : 240, quality : 90},
        // Rename files by clicking on their titles
        rename: true,
        // Sort files
        sortable: true,
        // Specify what files to browse for
        filters: [
				{ title: "Image files", extensions: "jpg,gif,png" },
				{ title: "Zip files", extensions: "zip,avi" }
			],
        // Flash settings
        flash_swf_url: '../Script/uploadImages/plupload.flash.swf',
        // Silverlight settings
        silverlight_xap_url: '../Script/uploadImages/plupload.silverlight.xap',
        init: {
            StateChanged: function (up) {
                // Called when a file chunk has finished uploading
                if (up.state == plupload.STOPPED)
                    caricaTabellaFoto(categ);
            }
        }
    });

    // Client side form validation
    $('form').submit(function (e) {
        var uploader = $('#uploader').plupload('getUploader');
        // Files in queue upload them first
        if (uploader.files.length > 0) {
            // When all files are uploaded submit form
            uploader.bind('StateChanged', function () {
                if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
                    $('form')[0].submit();
                }
            });
            uploader.start();
        } else
            alert('You must at least upload one file.');
        return false;
    });



    //elimina immagini
    $('#elimina').click(function () {
        if (window.confirm("Eliminare le foto selezionate?")) {
            var request = $.ajax({ url: "/Foto/DeleteFoto", traditional: true, type: "POST", data: { album: categ, elenco_id: selected_id, elenco_path: selected_path} });
            request.done();
            caricaTabellaFoto(categ);
        }
    });

    $("#aggiorna_button").button().click(function () {
        caricaTabellaFoto(categ);
    });
    $("#rinomina_button").button().click(function () {
        $("#renameAlbumForm").dialog("open");
    });


    $("#dialog:ui-dialog").dialog("destroy");

});

function caricaTabellaFoto(categoria) {
    $('#tabImmagini').load('/Foto/LoadFoto', { 'id': categoria });
    //Seleziona immagini

}

function cliccaFoto(img) {
    foto = new Object();
    foto.id = $(img).attr("val");
    foto.path = $(img).attr("src");

    if (selected_id.indexOf(foto.id) >= 0) {
        selected_path.splice(selected_id.indexOf(foto.id), 1);
        selected_id.splice(selected_id.indexOf(foto.id), 1);
        $(img).css("opacity", "");
    }
    else {
        selected_id.push(foto.id);
        selected_path.push(foto.path);
        $(img).css("opacity", "0.4");
    }
}

function RenameAlbum(id, newName) {
    $.ajax({
        url: "../RenameAlbum",
        type: "POST",
        data: { newName: newName, id: id },
        success: function (data) {
            return data;
        }
    });
    return false;
}

function AlbumExist(newName) {
    $.ajax({
        url: "../AlbumExist",
        type: "POST",
        data: { Nome: newName },
        success: function (data) {
            return data;
        }
    });
    return false;
}
